<template>
  <div class="login-wrapper">
    <!-- ref相当于一个标记，用来获取dom，怎么获取，通过this.$refs.对应的ref属性值 -->
    <el-form :model="ruleForm" status-icon :rules="rules" class="login-ruleForm" ref="loginForm">
      <h3 class="login-title">叩丁狼客户管理系统</h3>
      <el-form-item prop="username">
        <el-input type="text" v-model="ruleForm.username" placeholder="请输入账号" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="pwd">
        <el-input type="password" v-model="ruleForm.pwd" placeholder="请输入密码" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" type="primary" @click="loginFn">登录</el-button>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
// ipconfig/flushdns 清理电脑缓存
export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        username: [
          // required:是否必填，如不设置，则会根据校验规则自动生成
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 10, message: "账号的长度是3-10", trigger: "blur" }
        ],
        pwd: [{ validator: this.validPwd, trigger: "blur" }]
      }
    };
  },
  methods: {
    validPwd(rule, value, cd) {
      // console.log(rule, value, cd);
      // 当前输入框的值是否为空
      if (!value) {
        cd("密码不能为空！");
      } else {
        cd();
      }
    },
    loginFn() {
      // ref相当于一个标记，用来获取dom，怎么获取，通过this.$refs.对应的ref属性值
      // this.$refs['loginForm'] 一样的
      // console.log(this.$refs.loginForm);
      this.$refs.loginForm.validate(vali => {
        // console.log(vali);
        if (vali) {
          console.log("通过校验");
          const params = {
            username: this.ruleForm.username,
            password: this.ruleForm.pwd
          };
          // qs库：axios自带的 stringify:将对象转为url参数格式
          console.log(qs.stringify(params)); //username=terry&password=1

          // 调用登录接口
          axios.post("/tokens", qs.stringify(params)).then(res => {
            console.log(res);

            if (res.data.success) {
              // 进入管理后台
            } else {
              // 提示错误
              this.$message.error(res.data.msg);
            }
          });
        } else {
          console.log("校验失败！");
        }
      });
    }
  }
};
</script>

<style lang="less"  scoped>
// scoped 局部样式，不会影响到组件外的其他样式，就算重名也不会影响到
.login-wrapper {
  background-color: #324057;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-ruleForm {
    width: 350px;
    height: 200px;
    .login-title {
      font-style: 24px;
      color: #fff;
      text-align: center;
      margin-bottom: 10px;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>